define(['jquery'], function ($) {
    new main().render();
});
var main = function mainAction() {
    var loadMore ='.loadMore';
    var target = this;
    var articleList = {
        page:2,
        pageSize: pageSize,
        total:total,
        elementUl:$('#content_list'),
        htmlEngine:$('#html-engine')
    };
    this.render = function () {
      $("img.lazy").lazyload({
            effect: "fadeIn",
            placeholder : "/statics/images/loading.gif",
        });
        $(loadMore).click(function () {
            target.loadMore();
        });
    }
    this.loadMore = function () {
        var promise = window.API.publicApi.getNewArticleList({
            page: articleList.page,
            pageSize: articleList.pageSize
        });
        promise.then(function (result) {
            if (result.status ==1) {
                if(result.data.total>0){
                    if (result.data.rows.length < articleList.pageSize && articleList.pageSize * articleList.page > articleList.total) {
                        $(loadMore).hide()
                    }
                    articleList.page = articleList.page+1;
                    articleList.total = result.data.total;
                    if(result.data.rows.length<=0){
                        $(loadMore).hide()
                    }else{
                        target.buildHtml(result.data.rows, 'append', $(articleList.elementUl), $(articleList.htmlEngine));
                    }
                }else{
                    // $('.noData').show();
                    $(loadMore).hide()
                }
            }
        });
    }
    this.buildHtml = function (result, type, element, elementTemplate) {
        var target = this;
        var htmls = [];
        var templateHtml = $(elementTemplate).html();
        for (var rowsKey in result) {
            var row = result[rowsKey];
            row['index'] = rowsKey;
            var engine = new HtmlTemplateEngine();
            engine.setMapper(target.buildMapper(row));
            htmls.push(engine.buildText(templateHtml));
        }
        if (type == 'prepend') {
            $(element).prepend(htmls.join(''));
        } else {
            $(element).append(htmls.join(''));
        }
    };
    this.buildMapper = function (row) {
        var target = row;
        var tags ='  <i class="fa fa-tags"></i>';
        if( !target.tags){
            tags='';
        }
        for(var i in target.tags){
            tags+='<a href="'+target.tags[i]['tag_url']+'" target="_blank">'+target.tags[i]['text']+'</a>';
        }
        target.imgs = ' <img src="'+target.cover_image+'" onerror="this.src=\'/statics/images/245X138.jpg\'"  title="'+target.title+'" alt>';

        target.tags =tags;
        return target;
    };
}